package com.yjymm.edu.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yjymm.edu.model.entity.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yjymm
 * @date 2021-01-13 23:16
 */
public class LoginUserContext {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static ThreadLocal<User> localUser = new ThreadLocal<>();

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public static User getUser() {
        return localUser.get();
    }

    public static Integer getUserId() {
        return localUser.get().getId();
    }

    public static String getUserName() {
        return localUser.get().getUsername();
    }

    public static void setUser(User loginUser) {
        localUser.set(loginUser);
    }

    public static void removeUser() {
        localUser.remove();
    }

    public static Map<String, Object> getUserHeaderMap() {
        User loginUser = getUser();
        if (loginUser != null) {
            return objectMapper.convertValue(loginUser, HashMap.class);
        }
        return new HashMap<>();
    }
}
